<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

header('Content-Type: text/html; charset=utf-8');
require_once APPPATH.'third_party/simplehtmldom/simple_html_dom.php';
/**
* @property CI_DB_active_record $db
* @property CI_DB_forge $dbforge
* @property CI_Config $config
* @property CI_Loader $load
* @property CI_Session $session
*/

class Js extends CI_Controller {

    public function index()
    {
        if(isset($_GET)){
            if(isset($_GET['api_key']) and isset($_GET['site'])){
                $api_key = $_GET['api_key'];
                $site = $_GET['site'];
                $this->load->model('Main_model');
                $check_valid = $this->Main_model->chech_valid_api($api_key, $site);
                if($check_valid){
                    $res = $this->start_scraping($site);
                    $get_subs_list = $this->Main_model->get_subs_list();
                    $tmp = $this->replace_affiliate($res, $get_subs_list);
                    echo $tmp;
                }
            }
        }
    }
    
    public function start_scraping($site){
        $html = new simple_html_dom();
        $html->load_file("http://localhost/test.com/");
        foreach($html->find('#fb') as $div)
            $d = $div->innertext;
        $html->clear();
        return $d;
    }
    
    public function replace_affiliate($html, $list_subsc){
        foreach($list_subsc as $sub){
            $domain = $this->separate_dotcom($sub);
            $link = $this->make_link($domain, $sub);
            $html = preg_replace("/$domain/i", $link, $html);
        }
        return $html;
    }
    
    public function separate_dotcom($string){
        preg_match("/(.*?)\./i", $string, $m);
        return $m[1];
    }
    
    public function make_link($str, $link){
        return '<a href="http://'. $link .'">'.$str.'</a>';
    }
        
}